#include "texture.h"
#include "../../base/logger.h"

OPEN_JLIB_NS


Texture::~Texture () {
  clear();
}

bool Texture::init (GLsizei w, GLsizei h, GLenum fmt, GLenum type, const GLvoid* data, const TexParam& param) {
  clear();
  glGenTextures(1, &_id);
  glBindTexture(GL_TEXTURE_2D, _id);
  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _w = w, _h = h, 0, fmt, type, data);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, param.minFilter);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, param.magFilter);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, param.wrapS);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, param.wrapT);
  return true;
}

bool Texture::reload (GLsizei w, GLsizei h, GLenum fmt, GLenum type, const GLvoid* data) {
  if (!_id || !data)
    return false;
  glBindTexture(GL_TEXTURE_2D, _id);
  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _w = w, _h = h, 0, fmt, type, data);
  return true;
}

void Texture::setParam (const TexParam& param) {
  if (!_id)
    return;
  glBindTexture(GL_TEXTURE_2D, _id);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, param.minFilter);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, param.magFilter);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, param.wrapS);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, param.wrapT);
}

void Texture::bind (GLuint bindingPoint) {
  debug_assert(valid());
  glActiveTexture(GL_TEXTURE0 + bindingPoint);
  glBindTexture(GL_TEXTURE_2D, _id);
}

void Texture::clear () {
  if (_id) {
    glDeleteTextures(1, &_id);
    _id = 0;
  }
}




bool TexFrame::init (Texture* tex) {
  if (!tex)
    return false;
  _tex = tex;
  _rect = {0.0F, 0.0F, 1.0F, 1.0F};
  return true;
}

bool TexFrame::init (Texture* tex, const Box2& rect) {
  if (!tex)
    return false;
  _tex = tex;
  _rect = rect;
  return true;
}


CLOSE_JLIB_NS
